package com.yunxiang.controller;

import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.jfinal.weixin.sdk.api.SnsAccessToken;
import com.jfinal.weixin.sdk.api.SnsAccessTokenApi;
import com.jfinal.weixin.sdk.api.UserApi;
import com.jfinal.weixin.sdk.jfinal.ApiController;
import com.yunxiang.service.DriverService;

public class LoginController extends ApiController{

	private DriverService driverService = new DriverService();
	public void getOpenId(){
		//从session中获取openId，若session中有值，则不需要向微信请求数据，直接跳转到指定页面即可
		//如果session中没有数据，则要先向微信请求获取用户openId
//		setSessionAttr("openId", "oc8Tfw8keVO5Rh8obmQ2Y6yKfFuc");
		String openId = getSessionAttr("openId");
		if(openId == null){
			//向微信服务器请求获取openId，通过微信网页授权接口
			String appId = ApiConfigKit.getApiConfig().getAppId();
			String redirectURL = Common.HOST + Common.PROJECT + "/login/redirectURL";
			String state = getPara("pageName");
			boolean snsapiBase = true;
			String authorizeURL = SnsAccessTokenApi.getAuthorizeURL(appId,redirectURL,state,snsapiBase);
			redirect(authorizeURL);
		}else{
			dispatcherPage(getPara("pageName"));
		}
	}
	
	public void redirectURL(){
		String code = getPara("code");
		String pageName = getPara("state");
		SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(ApiConfigKit.getApiConfig().getAppId(), ApiConfigKit.getApiConfig().getAppSecret(), code);
		String openId = snsAccessToken.getOpenid();
		setSessionAttr("openId", openId);
		dispatcherPage(pageName);
	}
	
	private void dispatcherPage(String pageName){
		String openId = getSessionAttr("openId");
		if(driverService.isBind(openId)){			//openId已绑定车牌号
			redirect(Common.HOST + Common.PROJECT + "/" + pageName);
		}else{
			redirect(Common.HOST + Common.PROJECT + "/bind.jsp");
		}
	}

	/**
	 * 如果要支持多公众账号，只需要在此返回各个公众号对应的  ApiConfig 对象即可
	 * 可以通过在请求 url 中挂参数来动态从数据库中获取 ApiConfig 属性值
	 */
	public ApiConfig getApiConfig() {
		ApiConfig ac = new ApiConfig();
		
		// 配置微信 API 相关常量
		ac.setToken(PropKit.get("token"));
		ac.setAppId(PropKit.get("appId"));
		ac.setAppSecret(PropKit.get("appSecret"));
		
		/**
		 *  是否对消息进行加密，对应于微信平台的消息加解密方式：
		 *  1：true进行加密且必须配置 encodingAesKey
		 *  2：false采用明文模式，同时也支持混合模式
		 */
		ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
		ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
		return ac;
	}
	
}
